{% extends 'manage.html' %}
{% load static %}
{% block title %}
    项目管理-文件
{% endblock %}

{% block css %}
    <style>
        .error-msg {
            color: red;
            position: absolute;
            font-size: 13px;
        }

        .card {
            width: 90%;
            margin: 10px auto;
        }

        .title_header {
            margin-top: 10px;
            display: flex;
            flex-direction: row;
            justify-content: space-between;
            margin-left: 10px;
            margin-right: 10px;
        }

        .tbody {
            color: gray;
        }

        .a_style:hover {
            text-decoration: none;
        }


        .upload_left {
            overflow: hidden;
            position: relative;
        }

        .upload_left > input {
            opacity: 0;
            position: absolute;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            width: 100%;
            height: 100%;
            cursor: pointer;
        }

        .upload_progress {
            position: fixed;
            width: 400px;
            right: 2px;
            bottom: 2px;
        }

        .hide {
            display: none !important;
        }

        .card-body {
            background-color: white;
        }

        .progress_error {
            color: red;
        }
    </style>
{% endblock %}


{% block content %}



    <div class="modal fade" id="addModal" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="exampleModalLabel"></h5>
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                        <span aria-hidden="true">&times;</span>
                    </button>
                </div>
                <div class="modal-body">
                    <form id="addForm">
                        {% csrf_token %}
                        <input type="hidden" name="fid" id="fid" value="">

                        {% for item in form %}
                            <div class="form-group">
                                <label for="{{ item.id_for_label }}">{{ item.label }}</label>
                                {{ item }}
                                <span class="error-msg"></span>
                            </div>
                        {% endfor %}
                    </form>

                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-dismiss="modal">取 消</button>
                    <button type="button" class="btn btn-primary " id="SubmitBtn">确 定</button>
                </div>
            </div>
        </div>
    </div>

    <!-- Modal -->
    <div class="modal fade" id="alertModal" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true">
        <div class="modal-dialog">

            <div class="modal-content ">
                <div class="alert alert-danger alert-dismissible fade show " style="margin-bottom: 0" role="alert">
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                        <span aria-hidden="true">&times;</span>
                    </button>
                    <h4 class="alert-heading">是否确定删除?</h4>
                    <p>文件夹中所有的文件夹和文件都将被删除</p>

                    <p style="text-align: right">
                        <button type="button" class="btn btn-secondary" data-dismiss="modal">取 消</button>
                        <button id="btnDelete" type="button" class="btn btn-danger">确 定</button>
                    </p>
                </div>
            </div>


        </div>
    </div>

    <div class="card">
        <div class="title_header">
            <div>
                <a href="{% url 'manage:file_list' project_id=request.tracer.project.id %}" class="a_style"><i
                        class="fas fa-home"></i> 文件库</a>
                {% for item in nav_list %}
                    <a href="{% url 'manage:file_list' project_id=request.tracer.project.id %}?folder={{ item.id }}"
                       class="a_style"> >
                        {{ item.name }}</a>
                {% endfor %}
            </div>
            <div class="upload">
                <div class="upload_left btn btn-primary">

                    <input type="file" multiple name="uploadFile" id="uploadFile">
                    <div>
                        <i class="fa fa-file-upload"></i> 上传文件
                    </div>
                </div>


                <a type="button" class="btn btn-primary" data-toggle="modal" data-target="#addModal"
                   data-whatever="新建文件夹">
                    <i class="far fa-folder"></i> 新建文件夹
                </a>


            </div>
        </div>

        <div class="card-body">
            <blockquote class="blockquote mb-0">
                <table class="table">
                    <thead>
                    <tr>
                        <th>名称</th>
                        <th>文件大小</th>
                        <th>更新者</th>
                        <th>更新时间</th>
                        <th>操作</th>
                    </tr>
                    </thead>
                    <tbody class="tbody rowList">
                    {% for item in file_obj_list %}
                        <tr>
                            <td>
                                {% if item.file_type == 2 %}
                                    <a href="{% url 'manage:file_list' project_id=request.tracer.project.id %}?folder={{ item.id }}"
                                       class="a_style">
                                        <i class="fas fa-folder"></i>
                                        {{ item.name }}
                                    </a>
                                {% else %}
                                    <i class="fas fa-file"></i>
                                    {{ item.name }}
                                {% endif %}

                            </td>
                            <td>
                                {% if item.file_type == 1 %}
                                    {{ item.file_size }}
                                {% else %}
                                    ---
                                {% endif %}
                            </td>
                            <td>
                                {{ item.update_user.username }}
                            </td>
                            <td>
                                {{ item.update_datetime }}
                            </td>
                            <td>
                                {% if item.file_type == 2 %}
                                    <a class="a_style btn btn-primary"
                                       data-toggle="modal"
                                       data-target="#addModal"
                                       data-whatever="编辑文件夹"
                                       data-fid="{{ item.id }}"
                                       data-name="{{ item.name }}"
                                    >
                                        <i class="fas fa-edit"></i>
                                    </a>
                                {% else %}
                                    <a class="btn btn-primary download"
                                       href="{% url 'manage:file_download' project_id=request.tracer.project.id file_id=item.id %}">
                                        <i class="fas fa-cloud-download-alt" aria-hidden="true"></i>
                                    </a>
                                {% endif %}
                                <a class="a_style btn btn-danger"
                                   data-toggle="modal"
                                   data-target="#alertModal"
                                   data-fid="{{ item.id }}"
                                ><i class="fas fa-trash-alt"></i></a>
                            </td>
                        </tr>
                    {% endfor %}
                    </tbody>
                </table>
            </blockquote>
        </div>
    </div>

    <div id="uploadProgress" class="upload_progress hide">
        <div class="card text-white bg-primary mb-3">
            <div class="card-header"><i class="fa fa-arrow-circle-up"></i> 上传进度</div>
            <div class="card-body">
                <table class="table">
                    <tbody id="progressList">

                    </tbody>
                </table>
            </div>
        </div>
    </div>

    <div class="hide">
        <table id="progressTemplate">
            <tr>
                <td>
                    <div class="name"></div>
                    <div class="progress">
                        <div class="progress-bar" role="progressbar" style="width: 0;" aria-valuenow="0"
                             aria-valuemin="0" aria-valuemax="100">0%
                        </div>
                    </div>
                    <div class="progress_error"></div>
                </td>
            </tr>
        </table>
    </div>

    <div class="hide">
        <table id="rowTpl">
            <tr>
                <td>
                    <i class="fas fa-file"></i> <span class="name"></span>
                </td>
                <td class="file_size"></td>
                <td class="update_user_username"></td>
                <td class="update_datetime"></td>
                <td>
                    <a class="btn btn-primary download">
                        <i class="fas fa-cloud-download-alt" aria-hidden="true"></i>
                    </a>
                    <a class="a_style btn btn-danger delete" data-toggle="modal" data-target="#alertModal">
                        <i class="fas fa-trash-alt" aria-hidden="true"></i>
                    </a>
                </td>
            </tr>
        </table>

    </div>

{% endblock %}

{% block js %}
    <script src="{% static 'js/cos-js-sdk-v5.min.js' %}"></script>
    <script>
        var FILE_DELETE_URL = "{% url 'manage:file_delete' project_id=request.tracer.project.id %}"
        var COS_CREDENTIAL = "{% url 'manage:cos_credential' project_id=request.tracer.project.id %}"
        var FILE_POST = "{% url 'manage:file_post' project_id=request.tracer.project.id %}"

        // 拿到cos对象

        // 页面加载完成字段执行
        $(function () {
            BindSubmitBtn();
            ClearModalOnClose();
            BindModalShowEvent(); // 新增：绑定模态框显示事件
            BindBtnDelete(); // 绑定删除事件
            BindUploadFile(); // 绑定上传文件
        });

        function BindUploadFile() {

            $('#uploadFile').change(function () {
                var file_list = $(this)[0].files   // 所有的文件对象
                var checkFilelList = []
                var completedCount = 0;
                // 获取本次要上传的每个文件名称及大小
                $.each(file_list, function (index, fileObject) {
                    {#var fileName = fileObject.name;#}
                    {#var filesize = fileObject.size;#}
                    checkFilelList.push({'name': fileObject.name, 'size': fileObject.size})
                })

                // 把这些数据发送到后端， 进行容量校验, 如果容量没问题则返回临时凭证， 否则返回错误信息
                var COS_OBJECT = new COS({
                    getAuthorization: function (options, callback) {
                        // 想django后台发送请求，获取临时凭证
                        $.post(COS_CREDENTIAL, JSON.stringify(checkFilelList),
                            function (res) {
                                if (res.status) {
                                    var credentials = res.data && res.data.credentials;
                                    if (!res.data || !credentials) return console.error('credentials invalid');
                                    callback({
                                        TmpSecretId: credentials.tmpSecretId,
                                        TmpSecretKey: credentials.tmpSecretKey,
                                        XCosSecurityToken: credentials.sessionToken,
                                        StartTime: res.data.startTime,
                                        ExpiredTime: res.data.expiredTime,
                                    });
                                    // 在 BindUploadFile 函数中，文件上传开始时
                                    $('#uploadProgress').removeClass('hide').show();
                                } else {
                                    alert(data.error)
                                }

                            });
                    }
                });

                // 上传文件
                $.each(file_list, function (index, fileObject) {
                    // $('#progressList').empty();
                    var fileName = fileObject.name;
                    var fileSize = fileObject.size;
                    var key = (new Date()).getTime() + '_' + fileName
                    // 拿到tr这一行
                    var tr = $('#progressTemplate').find('tr').clone()
                    tr.find('.name').text(fileName)
                    $('#progressList').append(tr)
                    // 上传文件
                    COS_OBJECT.putObject({
                        Bucket: '{{ request.tracer.project.bucket }}', /* 必须 */
                        Region: '{{ request.tracer.project.region }}',     /* 存储桶所在地域，必须字段 */
                        Key: key,              /* 必须 */
                        Body: fileObject, // 上传文件对象
                        onProgress: function (progressData) {
                            // console.log("文件上传进度--->", fileName, JSON.stringify(progressData));
                            var percent = progressData.percent * 100 + '%'
                            tr.find('.progress-bar').text(percent);
                            tr.find('.progress-bar').css('width', percent);
                            // tr.find('.progress-bar').attr('aria-valuenow', percent)
                        }
                    }, function (err, data) {
                        console.log(err || data);
                        if (data && data.statusCode == 200) {
                            // 当前文件上传成功
                            $.post(FILE_POST, {
                                'name': fileName,
                                'file_size': fileSize,
                                'key': key,
                                'parent': '{{ folder_obj.id }}',
                                'etag': data.ETag,
                                'file_path': data.Location
                            }, function (res) {
                                // 在数据库中写入成功，动态显示在页面上
                                var newTr = $('#rowTpl').find('tr').clone()
                                newTr.find('.name').text(res.data.name)
                                newTr.find('.file_size').text(res.data.file_size)
                                newTr.find('.file_type').text(res.data.file_type)
                                newTr.find('.update_user_username').text(res.data.update_user_usrname)
                                newTr.find('.update_datetime').text(res.data.update_datetime)
                                newTr.find('.delete').attr('data-fid', res.data.id)
                                newTr.find('.download').attr('href', res.data.download_url)

                                $('.rowList').append(newTr)
                                tr.remove()
                            })


                            // 增加完成计数
                            completedCount++;

                            // 如果所有文件都上传完成，隐藏进度条
                            if (completedCount === file_list.length) {
                                setTimeout(function () {
                                    $('#uploadProgress').addClass('hide');
                                }, 2000); // 2秒后隐藏，让用户看到完成状态

                            }

                            // 上传成功后将文件提交到后台，保存到数据库
                        } else {
                            tr.find('#progress_error').text('上传失败')
                        }
                    });
                })

            })
        }


        function BindBtnDelete() {
            $('#btnDelete').click(function () {
                $.ajax({
                        url: FILE_DELETE_URL,
                        type: 'GET',
                        data: {
                            fid: $(this).attr('fid')
                        },
                        success: function (res) {
                            if (res.status) {
                                location.reload();
                            }
                        }
                    }
                )
            })
        }

        // 新增：绑定模态框显示前的事件
        function BindModalShowEvent() {
            $('#addModal').on('show.bs.modal', function (event) {
                var button = $(event.relatedTarget); // 触发模态框的按钮或链接
                var recipient = button.data('whatever'); // 获取 data-whatever 的值 ('新建文件夹' 或 '编辑文件夹')
                var modal = $(this);

                // 1. 设置模态框标题
                modal.find('.modal-title').text(recipient);

                // 2. 根据操作类型进行不同的初始化
                if (recipient === '编辑文件夹') {
                    var fid = button.data('fid');
                    var name = button.data('name');

                    // 预填充文件夹名称到表单（文件夹名称输入框的ID是 id_name）
                    $('#id_name').val(name || '');

                    // 存储文件夹ID到隐藏域
                    $('#fid').val(fid || '');

                } else {
                    // 新建文件夹：确保所有字段都被清空
                    $('#id_name').val(''); // 清空文件夹名称
                    $('#fid').val(''); // 清空 ID
                }
            });

            $('#alertModal').on('show.bs.modal', function (event) {
                var button = $(event.relatedTarget); // 触发模态框的按钮
                var fid = button.data('fid');
                // 将fid存储在删除按钮的data和attr中
                var $btnDelete = $('#btnDelete');
                $btnDelete.data('fid', fid);
                $btnDelete.attr('fid', fid); // 同时设置attr，双重保险
            });
        }

        // 新增函数：清除模态框内容和错误信息
        function ClearModalOnClose() {
            $('#addModal').on('hidden.bs.modal', function (e) {
                // 1. 清除表单内容（包括id_name和fid）
                $('#addForm')[0].reset();

                // 2. 清除所有错误信息
                $('.error-msg').text('');
            });
        }

        function BindSubmitBtn() {
            $('#SubmitBtn').click(
                function () {
                    // 发送ajax请求
                    $.ajax({
                            url: location.href,
                            type: 'POST',
                            data: $('#addForm').serialize(),
                            dataType: 'JSON',
                            //回调函数
                            success: function (res) {
                                if (res.status) {
                                    // 成功后刷新页面
                                    $('#addModal').modal('hide'); // 先关闭模态框
                                    location.reload(); // 刷新页面
                                } else {
                                    // 失败时显示错误信息
                                    // 先清空所有错误信息
                                    $('.error-msg').text('');
                                    $.each(res.error, function (key, value) {
                                        $('#id_' + key).next().text(value[0])
                                    })
                                }
                            }
                        }
                    )
                }
            )
        }


    </script>
{% endblock %}